<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        body,html {
            margin: 0;

        }

        #waterFull{
            width: 800px;
            margin: 0 auto;
            display: flex;
            justify-content: center;
        }
        .item {
            flex-basis: 20%;
        }
        img{
            width: 100%;
            height: auto;
            display: block;
        }
    </style>
</head>
<body>
    <div id="waterFull">
        <div class="item">
            <div id="box1"><img src="./imgs/2.jpg" alt=""></div>
        </div>
        <div class="item">
            <div id="box2"><img src="./imgs/1.jpg" alt=""></div>
        </div>
        <div class="item">
            <div id="box3">
                <img src="./imgs/5.jpg" alt="">
            </div>
        </div>
        <div class="item">
            <div id="box4">
                <img src="./imgs/3.jpg" alt="">
            </div>
        </div>
        <div class="item">
            <div id="box5"><img src="./imgs/4.jpg" alt=""></div>
        </div>
    </div>
    <script>
        window.onload = function() {
            const imgs = ['./imgs/1.jpg', './imgs/2.jpg', './imgs/3.jpg', './imgs/4.jpg', './imgs/5.jpg']
            // 获取所有的瀑布项盒子
            const els = Array.from(document.getElementsByClassName('item')) 
            // 获取屏幕高度 设置当最小的瀑布高度大于屏幕高度停止瀑布流
            const clientH = document.documentElement.clientHeight
             var timer
            function waterFull() {
                var arr = [] // 用来收集说有的元素及高度信息
                els.forEach(item => {
                    let obj = {
                        el: item.getElementsByTagName('div')[0],
                        height: item.getElementsByTagName('div')[0].offsetHeight
                    }
                    arr.push(obj)
                })
                // console.log(arr)
                // 排序找出高度最小的容器盒
                arr.sort((a, b) => {
                    return a.height - b.height
                })
                // 随机一张图片的函数
                function randomImg() {
                    return imgs[Math.round(Math.random()*4)]
                }
                if(arr[0].height > clientH) {
                    clearInterval(timer)
                    return
                } else {
                    var img = `<img src=${randomImg()}>`
                    arr[0].el.insertAdjacentHTML('beforeEnd', img)
                }
               
            }
            timer = setInterval(() => {
                    waterFull()
            },300)
        }
    </script>
</body>
</html>